package com.ljw.punishment.baserule;

import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.support.composite.UnitRuleGroup;

import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;
import java.util.Set;

/**
 * 在 Easy Rules 中，CompositeRule 是一种组合规则，它可以包含多个子规则（Rule）
 * UnitRuleGroup extends CompositeRule
 * @author lijunwei
 * @date 2025/5/21
 */
@Slf4j
public class AndRelationGroup extends UnitRuleGroup implements Serializable, Comparable<Rule>{

    private static final long serialVersionUID = -6833719425496169006L;

    private Integer id;
    private String name;
    private String description;
    private int priority;
    private String rewardCode;

    public AndRelationGroup(Integer id, String name, String rewardCode, Set<CommonRule> rules) {
        super(name, "AndRelationGroup : { id =  " + id + ",name = " + name + ",rewardCode = " + rewardCode + "}");
        this.name = name;
        this.id = id;
        this.rewardCode = rewardCode;
        this.description = "AndRelationGroup : { id =  " + id + ",name = " + name + ",rewardCode = " + rewardCode + "}";

        for (CommonRule rule : rules) {
            addRule(rule);
        }

    }

    @Override
    public String toString() {
        return "AndRelationGroup{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", priority=" + priority +
                ", rewardCode='" + rewardCode + '\'' +
                '}';
    }

    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        out.writeObject(super.rules);
    }

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        super.rules = (Set<Rule>)in.readObject();
    }

    @Override
    public int compareTo(Rule rule) {
        if (rule == null) {
            return -1;
        }

        if (rule.getName().equals(this.name) && rule.getDescription().equals(this.description)) {
            return 1;
        } else {
            return -1;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
        AndRelationGroup that = (AndRelationGroup) o;
        return id.equals(that.id) && name.equals(that.name) && rewardCode.equals(that.rewardCode);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), id, name, rewardCode);
    }
}